package xml.ex.student.client;


import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

import xml.ex.student.entity.StudentEntity;
import xml.ex.student.service.StudentService;

public class StudentClient {
	
	
	/**
	 * 初始化学生 添加学生
	 * @throws Exception
	 */
	@Test
	public void add() throws Exception {
		StudentService service = new StudentService();
		List<StudentEntity> allStudent = service.getAllStudent();
		
		//建立一个xml文档
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("students");
		
		for (StudentEntity student : allStudent) {
			service.insertNode(student, root);
		}
		
		//输出格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		//设置是否缩进
		format.setIndent(true);
		//缩进多少
		format.setIndent("\t");
		//是否换行
		format.setNewlines(true);
		
		
		
		
		//写到到指定的文件
		XMLWriter writer=new XMLWriter(new FileWriter("src/student.xml"),format);
		writer.write(document);
		
		writer.close();
		
		//打印到控制台
		//用来存放xml
		StringWriter stringWriter = new StringWriter();
		
		XMLWriter kztwriter = new XMLWriter(stringWriter,format);
		//将xml写到stringWriter中
		kztwriter.write(document);
		
		System.err.println(stringWriter);
		kztwriter.close();
		
	}
	
	/**
	 * 根据id删除
	 * @throws Exception
	 */
	@Test
	public void  deleteById() throws Exception {
		SAXReader reader=new SAXReader();
		Document document = reader.read(new File("src/student.xml"));
		List<Element> nodes = document.selectNodes("//student");
		for (Element e : nodes) {
			String idvalue = e.attributeValue("id");
			if(idvalue.equals(""+2)){
				e.getParent().remove(e);
				break;
			}
			
		}
		//把内存中的document写入到硬盘中
		PrintWriter pw=new PrintWriter("src/student.xml");
		OutputFormat format=new OutputFormat();
		format.setEncoding("utf-8");
		format.setIndent(true);
		format.setIndent("\t");
		format.setNewlines(true);
		
		
		XMLWriter writer=new XMLWriter(pw,format);
		writer.write(document);
		writer.flush();
		writer.close();
	}
	
	@Test
	public void update() throws Exception {
		StudentEntity s2 = new StudentEntity();
		s2.setId(1);
		s2.setName("刘浩2");
		s2.setAge(23);
		s2.setMajor("全能");
		
		SAXReader reader=new SAXReader();
		Document document = reader.read(new File("src/student.xml") );
		List<Element> nodes = document.selectNodes("//student");
		
		for (Element e : nodes) {
			String idvalue = e.attributeValue("id");
			if(idvalue.equals(""+1)){
				Element name = e.element("name");
				name.setText(s2.getName());
				break;
			}
			
		}
		
		
	}
	

}
